//
//  AppDelegate.m
//  testassembly
//
//  Created by liangang on 2018/3/8.
//  Copyright © 2018年 liangang. All rights reserved.
//

#import "AppDelegate.h"
#import "YTKNetworkConfig.h"
#import "homeApi.h"
//#import "CYLTabBarController.h"
#import "tabBarModel.h"
#import "ViewController.h"
#import "UIColor+hex.h"
#import "INTULocationManager.h"
//#import "baseTabBarViewController.h"
#import "YTKNetworkConfig.h"
#import <AlipaySDK/AlipaySDK.h>
#import "detailViewController.h"
#import <ShareSDK/ShareSDK.h>
#import  <ShareSDKConnector/ShareSDKConnector.h>
#import "WXApi.h"
@interface AppDelegate ()<WXApiDelegate>
{
    tabBarModel *tabModel;
}
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    
    
    [ShareSDK registerActivePlatforms:@[@(SSDKPlatformTypeWechat)] onImport:^(SSDKPlatformType platformType) {
//        switch (platformType)
//        {
//            case SSDKPlatformTypeWechat:
//                [ShareSDKConnector connectWeChat:[WXApi class]];
//                break;
//        }
        if (platformType == SSDKPlatformTypeWechat) {
            [ShareSDKConnector connectWeChat:[WXApi class]];
            
        }
    } onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
        if (platformType == SSDKPlatformTypeWechat) {
            [ShareSDKConnector connectWeChat:[WXApi class]];
            [appInfo SSDKSetupWeChatByAppId:@"wxa1872048b20fa965"
                                  appSecret:@"0f3438da82e6e835e783d288d003600f"];
        
        }
    }];
    [WXApi registerApp:@"wxa1872048b20fa965"];
    
    
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self httpConfig];
    self.tabBar=[AppDelegate creatTabBar];
    self.window.rootViewController =self.tabBar;
    
    [self.window makeKeyAndVisible];
    
//    NSDictionary *myDictionary = @{@"tabbar" : @{@"bgColor" : @"#FFFFFF",
//                                                 @"items" : @[@{@"name" : @"智慧党建",
//                                                                @"image" : @"XX.png",
//                                                                @"selectImage" : @"XX.png",
//                                                                @"textColor" : @"#CC00FF",
//                                                                @"selectColor" : @"#2F4F4F",
//                                                                @"vc" : @{@"layout" : @{@"view1" : @""},
//                                                                          @"name" : @"XXX",
//                                                                          @"argument" : @{@"a" : @"1",
//                                                                                          @"b" : @"2"}}},
//                                                              @{@"name" : @"智慧党建",
//                                                                @"image" : @"XX.png",
//                                                                @"selectImage" : @"XX.png",
//                                                                @"textColor" : @"#CC00FF",
//                                                                @"selectColor" : @"#2F4F4F",
//                                                                @"vc" : @{@"layout" : @{@"view1" : @""},
//                                                                          @"name" : @"XXX",
//                                                                          @"argument" : @{@"a" : @"1",
//                                                                                          @"b" : @"2"}}},
//                                                              @{@"name" : @"智慧党建",
//                                                                @"image" : @"XX.png",
//                                                                @"selectImage" : @"XX.png",
//                                                                @"textColor" : @"#CC00FF",
//                                                                @"selectColor" : @"#2F4F4F",
//                                                                @"vc" : @{@"layout" : @{@"view1" : @""},
//                                                                          @"name" : @"XXX",
//                                                                          @"argument" : @{@"a" : @"1",
//                                                                                          @"b" : @"2"}}},
//                                                              @{@"name" : @"智慧党建",
//                                                                @"image" : @"XX.png",
//                                                                @"selectImage" : @"XX.png",
//                                                                @"textColor" : @"#CC00FF",
//                                                                @"selectColor" : @"#2F4F4F",
//                                                                @"vc" : @{@"layout" : @{@"view1" : @""},
//                                                                          @"name" : @"XXX",
//                                                                          @"argument" : @{@"a" : @"1",
//                                                                                          @"b" : @"2"}}}]}};
//
//
//
//
//    NSLog(@"%@",[self DataTOjsonString:myDictionary]);
//    homeApi  *api = [[homeApi alloc]init];
//    api.appName = @"智天下";
//    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest *request) {
//        NSLog(@"%@",request.responseString);
//        NSDictionary *dic = request.responseJSONObject[@"tabbar"];
//
//
//        tabModel =[[tabBarModel alloc]init];
//        [tabModel setValuesForKeysWithDictionary:dic];
//        NSLog(@"111");
//        baseTabBarViewController *tab = [[baseTabBarViewController alloc]init];
//        tab.tabBarSourceModel = tabModel;
////        ViewController   *vc = [[ViewController   alloc]init];
//        self.window.rootViewController = tab;
//        [self.window makeKeyAndVisible];
//    } failure:^(__kindof YTKBaseRequest *request) {
//
//
//
//        NSLog(@"%@",request.responseString);
//    }];
    
    if ([[[[NSUserDefaults standardUserDefaults]dictionaryRepresentation]allKeys]containsObject:@"cookie"]) {
        //获取cookies：程序起来之后，uiwebview加载url之前获取保存好的cookies，并设置cookies，
        NSArray *cookies =[[NSUserDefaults standardUserDefaults]  objectForKey:@"cookie"];
        NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
        [cookieProperties setObject:[cookies objectAtIndex:0] forKey:NSHTTPCookieName];
        [cookieProperties setObject:[cookies objectAtIndex:1] forKey:NSHTTPCookieValue];
        [cookieProperties setObject:[cookies objectAtIndex:3] forKey:NSHTTPCookieDomain];
        [cookieProperties setObject:[cookies objectAtIndex:4] forKey:NSHTTPCookiePath];
        NSHTTPCookie *cookieuser = [NSHTTPCookie cookieWithProperties:cookieProperties];
        [[NSHTTPCookieStorage sharedHTTPCookieStorage]  setCookie:cookieuser];
    }
    
    return YES;
}
//-(void)initLocation
//{
//    INTULocationManager *locMgr = [INTULocationManager sharedInstance];
//    // 获取当前位置
//    [locMgr requestLocationWithDesiredAccuracy:INTULocationAccuracyRoom timeout:10.0 block:^(CLLocation *currentLocation, INTULocationAccuracy achievedAccuracy, INTULocationStatus status) {
//        
//        NSLog(@"%f %f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
//        self.location = currentLocation;
//    }];
//}
+(CYLTabBarController*)creatTabBar
{
    NSDictionary *myDictionary = @{@"tabbar" : @{@"bgColor" : @"#FFFFFF",
                                                 @"items" : @[
                                                            @{@"name" : @"车生活",
                                                                 @"image" : @"second",
                                                                 @"selectImage" : @"second_s",
                                                                 @"textColor" : @"#adadad",
                                                                 @"selectColor" : @"#2faff6",
                                                                 @"vc" : @{@"layout" : @"",
                                                                           @"name" : @"thirdViewController",
                                                                           @"routeUrl" : @""}},
                                                            @{@"name" : @"报名",
                                                                @"image" : @"first",
                                                                @"selectImage" : @"first_s",
                                                                @"textColor" : @"#adadad",
                                                                @"selectColor" : @"#2faff6",
                                                                @"vc" : @{@"layout" : @"",
                                                                          @"name" : @"firstViewController",
                                                                          @"routeUrl" : @""}},
                                                              @{@"name" : @"考试",
                                                                @"image" : @"third",
                                                                @"selectImage" : @"third_s",
                                                                @"textColor" : @"#adadad",
                                                                @"selectColor" : @"#2faff6",
                                                                @"vc" : @{@"layout" : @"",
                                                                          @"name" : @"secondViewController",
                                                                          @"routeUrl" : @""}},
                                                             
                                                              @{@"name" : @"我的",
                                                                @"image" : @"fourth",
                                                                @"selectImage" : @"fourth_s",
                                                                @"textColor" : @"#adadad",
                                                                @"selectColor" : @"#2faff6",
                                                                @"vc" : @{@"layout" : @"",
                                                                          @"name" : @"fourthViewController",
                                                                          @"routeUrl" : @""}}]}};
    tabBarModel     *tabModel = [[tabBarModel alloc ]init];
    [tabModel setValuesForKeysWithDictionary:myDictionary[@"tabbar"]   ];
    NSMutableArray *viewControllerArray = [[NSMutableArray alloc ]init];
    NSMutableArray *ItemsAttributes = [[NSMutableArray alloc]init ];
    CYLTabBarController *tab = [[CYLTabBarController alloc]init];
    [tabModel.items enumerateObjectsUsingBlock:^(tabBarItemModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        //        UINavigationController *nav = [[UINavigationController    alloc]initWithRootViewController:obj.vc.vc];
        //        [viewControllerArray addObject:nav];
        SDWebImageManager *manager = [SDWebImageManager sharedManager];
        [manager loadImageWithURL:[NSURL URLWithString:obj.image] options:SDWebImageProgressiveDownload    progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            
        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            
        }];
        
        UIImage *normalImage = [UIImage imageResize:[UIImage imageNamed:obj.image] andResizeTo:CGSizeMake(24, 19)];
        UIImage *slectImage = [UIImage imageResize:[UIImage imageNamed:obj.selectImage] andResizeTo:CGSizeMake(24, 19)];
        
        NSDictionary *dict = @{
                               CYLTabBarItemTitle : obj.name,
                               CYLTabBarItemImage : normalImage,
                               CYLTabBarItemSelectedImage : slectImage,
                               };
        [ItemsAttributes addObject:dict ];
    }];
    
    tab.tabBarItemsAttributes = ItemsAttributes;
    //    self.viewControllers  = viewControllerArray;
    ViewController   *vc1 = [[ViewController   alloc]init];
    vc1.url= WEBURL1;
    UINavigationController *nav1 = [[UINavigationController alloc]initWithRootViewController:vc1];
    ViewController   *vc2 = [[ViewController   alloc]init];
    vc2.url= WEBURL2;
    UINavigationController *nav2 = [[UINavigationController alloc]initWithRootViewController:vc2];
    ViewController   *vc3 = [[ViewController   alloc]init];
    vc3.url= WEBURL3;
    UINavigationController *nav3 = [[UINavigationController alloc]initWithRootViewController:vc3];
    ViewController   *vc4 = [[ViewController   alloc]init];
    vc4.url= WEBURL4;
    UINavigationController *nav4 = [[UINavigationController   alloc]initWithRootViewController:vc4];
    tab.viewControllers =@[nav3,nav1,nav2,nav4];
    tab.tabBar.translucent = NO;
    //        ViewController   *vc = [[ViewController   alloc]init];
    
    return tab;
}
-(void)httpConfig
{
    YTKNetworkConfig *config = [YTKNetworkConfig sharedInstance];
    config.baseUrl = @"https://www.lialoan.com";
    
}

//- (CYLTabBarController *)setupViewControllers {
//    NSMutableArray *viewControllerArray = [[NSMutableArray alloc ]init];
//    NSMutableArray *ItemsAttributes = [[NSMutableArray alloc]init ];
//    [tabModel.items enumerateObjectsUsingBlock:^(tabBarItemModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        UINavigationController *nav = [[UINavigationController    alloc]initWithRootViewController:obj.vc.vc];
//        [viewControllerArray addObject:nav];
//        UIImage *normalImage = [self imageResize:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:obj.image]]] andResizeTo:CGSizeMake(25, 25)];
//        UIImage *slectImage = [self imageResize:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:obj.selectImage]]] andResizeTo:CGSizeMake(25, 25)];
//
//        NSDictionary *dict = @{
//                                CYLTabBarItemTitle : obj.name,
//                                CYLTabBarItemImage : normalImage,
//                                CYLTabBarItemSelectedImage : slectImage,
//                                };
//        [ItemsAttributes addObject:dict ];
//    }];
//    CYLTabBarController *tabBarController = [[CYLTabBarController alloc] init];
//
//    tabBarController.tabBarItemsAttributes = ItemsAttributes;
//    tabBarController.viewControllers  = viewControllerArray;
//    [self customizeTabBarAppearance];
//    return tabBarController;
//
//}
//-(UIImage *)imageResize :(UIImage*)img andResizeTo:(CGSize)newSize
//{
//    CGFloat scale = [[UIScreen mainScreen]scale];
//
//    //UIGraphicsBeginImageContext(newSize);
//    UIGraphicsBeginImageContextWithOptions(newSize, NO, scale);
//    [img drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
//    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    return newImage;
//}



-(NSString*)DataTOjsonString:(id)object
{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}
- (void)customizeTabBarAppearance {
    
    //去除 TabBar 自带的顶部阴影
    [[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
    NSString *selectColor = ((tabBarItemModel *)tabModel.items[0]).selectColor;
    NSString *textColor =((tabBarItemModel *)tabModel.items[0]).textColor;
    // set the text color for unselected state
    // 普通状态下的文字属性
    NSMutableDictionary *normalAttrs = [NSMutableDictionary dictionary];
    normalAttrs[NSForegroundColorAttributeName] = [UIColor colorWithHexString:textColor];
    
    // set the text color for selected state
    // 选中状态下的文字属性
    NSMutableDictionary *selectedAttrs = [NSMutableDictionary dictionary];
    
    selectedAttrs[NSForegroundColorAttributeName] = [UIColor colorWithHexString:selectColor];
    
    // set the text Attributes
    // 设置文字属性
    UITabBarItem *tabBar = [UITabBarItem appearance];
    [tabBar setTitleTextAttributes:normalAttrs forState:UIControlStateNormal];
    [tabBar setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
    
    // Set the dark color to selected tab (the dimmed background)
    // TabBarItem选中后的背景颜色
//    [[UITabBar appearance] setSelectionIndicatorImage:[self imageFromColor:[UIColor colorWithRed:26 / 255.0 green:163 / 255.0 blue:133 / 255.0 alpha:1] forSize:CGSizeMake([UIScreen mainScreen].bounds.size.width / 5.0f, 49) withCornerRadius:0]];
    
    // set the bar background color
    // 设置背景图片
    // UITabBar *tabBarAppearance = [UITabBar appearance];
    // [tabBarAppearance setBackgroundImage:[UIImage imageNamed:@"tabbar_background_ios7"]];
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
    return  [WXApi handleOpenURL:url delegate:self];
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            if ([resultDic[@"resultStatus"] integerValue]==9000) {
                UIViewController *vc =      [webMethod sharedInstance].currentVC;
                [vc.navigationController popViewControllerAnimated:YES];
//                AppDelegate *delegat = [UIApplication sharedApplication].delegate;
//                [delegat.tabBar setSelectedIndex:3];
                self.tabBar = [AppDelegate creatTabBar];
                self.window.rootViewController = self.tabBar;
                [self.tabBar setSelectedIndex:3];
                detailViewController *dVC = [[detailViewController alloc]init];
                dVC.url = @"https://www.lialoan.com/Driver/order/merchant_order.html";
                dVC.hidesBottomBarWhenPushed = YES;
                [ [webMethod sharedInstance].currentVC.navigationController pushViewController:dVC animated:YES];
//                self.tabBar.tabBar.hidden = NO;
//                [self.tabBar setSelectedIndex:3];
            
//                detailViewController *dVC = [[detailViewController alloc]init];
//                dVC.url = url;
//                dVC.hidesBottomBarWhenPushed = YES;
//                [self.navigationController pushViewController:dVC animated:YES];
            }
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
   return  [WXApi handleOpenURL:url delegate:self];;
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
     return  [WXApi handleOpenURL:url delegate:self];
}
- (void)onResp:(BaseResp *)resp {
    
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        /**
         *  拿到支付结果进行相应的业务逻辑处理，一般通过通知的方式通知支付页面进行相应的信息提示
         *  在这里需要注意的是，微信官方文档给出的支付成功的判断是需要访问服务器后台核实才算是真的支付成功了
         */
        switch (resp.errCode) {
            case WXSuccess:
            {
                /**
                 *  （那么这里就需要请求后台核对支付结果）
                 */
                
                //strMsg = @"支付结果：成功！";
                //                [NotificationCenter postNotificationName:WxPaySucceedNoti object:nil];
//                NSLog(@"1支付结果：成功");
//                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"支付成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//                [alert show];
                //[self.payVC.navigationController popViewControllerAnimated:YES ];
                UIViewController *vc =      [webMethod sharedInstance].currentVC;
                [vc.navigationController popViewControllerAnimated:NO];
                //                AppDelegate *delegat = [UIApplication sharedApplication].delegate;
                //                [delegat.tabBar setSelectedIndex:3];
//                self.tabBar = [AppDelegate creatTabBar];
//                self.window.rootViewController = self.tabBar;
                [self.tabBar setSelectedIndex:3];
                detailViewController *dVC = [[detailViewController alloc]init];
                dVC.url = @"https://www.lialoan.com/Driver/order/merchant_order.html";
                dVC.hidesBottomBarWhenPushed = YES;
                [ [webMethod sharedInstance].currentVC.navigationController pushViewController:dVC animated:YES];
                
            }
                break;
                
            default:
                //strMsg = @"支付结果：失败！
            {
                NSLog(@"2支付结果：失败");
                
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"支付失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
            }
                //                [NotificationCenter postNotificationName:WxPayFailedNoti object:nil];
                break;
        }
        
    }
    
}
@end
